/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.inputQuestion;

import javax.inject.Inject;

import org.apache.commons.lang3.Validate;

import ru.irenproject.Action;
import ru.irenproject.Check;
import ru.irenproject.TestInputException;
import ru.irenproject.inputQuestion.InputQuestionProtos.RegexpPatternEditorShape;
import ru.irenproject.inputQuestion.InputQuestionProtos.SpacePreprocessMode;
import ru.irenproject.store.Stash;

import com.google.protobuf.Message;

public final class RegexpPatternEditor extends AbstractPatternEditor {
  public static final class SetOptionsInput {
    public SpacePreprocessMode spacePreprocessMode;
    public boolean caseSensitive;
  }

  @Stash private InputQuestionProtos.RegexpPatternEditor.Builder $;

  @Inject RegexpPatternEditor() {}

  @Override public RegexpPattern pattern() {
    return get($.getPattern(), RegexpPattern.class);
  }

  @Override protected void setPattern(Pattern pattern) {
    Validate.isInstanceOf(RegexpPattern.class, pattern);
    $.setPattern(pattern.id());
    pattern.addListener(this);
  }

  @Override public Message render() {
    RegexpPattern p = pattern();
    return RegexpPatternEditorShape.newBuilder()
        .setValue(p.value())
        .setMaxSize(RegexpPattern.MAX_SIZE)
        .setQualityPercent(p.qualityPercent())
        .setCaseSensitive(p.caseSensitive())
        .setSpacePreprocessMode(p.spacePreprocessMode())
        .setHasDefaultOptions(p.hasDefaultOptions())
        .build();
  }

  @Action(badInput = TestInputException.class)
  public void doSetOptions(SetOptionsInput in) {
    pattern().setSpacePreprocessMode(Check.inputNotNull(in.spacePreprocessMode));
    pattern().setCaseSensitive(in.caseSensitive);
  }
}
